package com.sdk;

import java.io.UnsupportedEncodingException;

import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

import android.annotation.SuppressLint;
import android.util.Log;

@SuppressLint("DefaultLocale")
public class WxpayUtils {

	/**
     * 构造签名
     * @param params
     * @param encode
     * @return
     * @throws UnsupportedEncodingException 
     */
    public static String createSign(Map<String, String> params, boolean encode) throws UnsupportedEncodingException {
        Set<String> keysSet = params.keySet();
        Object[] keys = keysSet.toArray();
        Arrays.sort(keys);
        StringBuffer temp = new StringBuffer();
        boolean first = true;
        for (Object key : keys) {
            if (first) {
                first = false;
            } else {
                temp.append("&");
            }
            temp.append(key).append("=");
            Object value = params.get(key);
            String valueString = "";
            if (null != value) {
                valueString = value.toString();
            }
            if (encode) {
                temp.append(URLEncoder.encode(valueString, "UTF-8"));
            } else {
                temp.append(valueString);
            }
        }
        return temp.toString();
    }
 
    /**
     * 构造签名
     * @param params
     * @param paternerKey
     * @return
     * @throws UnsupportedEncodingException 
     */
    public static String Sign(Map<String, String> params, String paternerKey) throws UnsupportedEncodingException {
        String string1 = createSign(params, false);
        Log.i("UNITY", "生成的支付信息签名1 createSign == " + string1);
        String stringSignTemp = string1 + "&key=" + paternerKey;
        Log.i("UNITY", "生成的支付信息签名2 stringSignTemp == " + stringSignTemp);
        String signValue = "";
        try {
        	signValue = MD5.GetMD5Code(stringSignTemp).toUpperCase();
            Log.i("UNITY", "生成的支付信息签名3 signValue == " + signValue);
		} catch (Exception e) {
			Log.i("UNITY", "生成的支付信息签名4 MD5校验失败 == " + e);
		}
        	return signValue;
        }
}
